package com.lsmgc.cms.util.upload;

import com.lsmgc.cms.constant.SysConstant;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class UploadService {

    public String uploadImg(FileItem img) {
        // 扩展名
        String ext = FilenameUtils.getExtension(img.getName());

        // 图片名称生成策略
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        // 图片名称一部分
        String format = df.format(new Date());

        // 随机三位数
        Random r = new Random();
        for (int i = 0; i < 3; i++) {
            format += r.nextInt(10);
        }

        // 实例化一个jersey
        Client client = new Client();

        // 保存数据库
        String path = "/upload/" + format + "." + ext;

        // 另一台服务器的请求路径是？
        String url = SysConstant.IMAGE_SERVER + path;
        // 设置请求路径
        WebResource resource = client.resource(url);

        // 发送开始
        resource.put(String.class, img.get());

        return path;
    }
}
